import {
  HttpException,
  Inject,
  Injectable,
  NestMiddleware,
} from "@nestjs/common";
import { Request, Response, NextFunction } from "express";
import { CacheRedisService } from "src/cache-redis/cache-redis.service";
import { User } from "src/entity/user.entity";
@Injectable()
export class UserMiddleware implements NestMiddleware {
  constructor(
    @Inject(CacheRedisService) private readonly redis: CacheRedisService
  ) {}
  async use(req: Request, res: Response, next: NextFunction) {
    const token = req.headers.token ?? "";
    if (!token) {
      throw new HttpException({ code: 501, msg: "令牌不存在" }, 200);
    }
    const data = await this.redis.get(token.toString());
    if (data === null) {
      throw new HttpException({ code: 502, msg: "令牌异常" }, 200);
    }
    const user = data;
    Object.assign(req.body, { user });
    next();
  }
}
